package com.sczmgk.syevaluation.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.sczmgk.syevaluation.R;

import com.sczmgk.syevaluation.dialog.DialogFactory;
import com.sczmgk.syevaluation.dialog.MessageDialog;
import com.sczmgk.syevaluation.entity.input.LoginInput;
import com.sczmgk.syevaluation.entity.output.AppVersion;
import com.sczmgk.syevaluation.entity.output.UserMetter;
import com.sczmgk.syevaluation.entity.output.UserMetterBean;
import com.sczmgk.syevaluation.utils.CommonUtils;
import com.sczmgk.syevaluation.utils.DownLoadApi;
import com.sczmgk.syevaluation.utils.FileUtil;
import com.sczmgk.syevaluation.utils.HttpTools;
import com.sczmgk.syevaluation.utils.MyLog;
import com.sczmgk.syevaluation.utils.SoundPlayUtils;
import com.sczmgk.syevaluation.utils.SpfUtil;
import com.sczmgk.syevaluation.utils.Tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sczmgk.syevaluation.utils.FileUtil.getAPKPath;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity {


    // UI references.
    private AutoCompleteTextView mAccountView;
    private EditText mWindowView;
    private View mProgressView;
    private View mLoginFormView;
    private static final String TAG = LoginActivity.class.getSimpleName();
    private Switch mSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mAccountView = (AutoCompleteTextView) findViewById(R.id.email);

        mWindowView = (EditText) findViewById(R.id.password);
        mWindowView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);


        if(SpfUtil.isLogin(this)){
            if(SpfUtil.getUserType(LoginActivity.this)==SpfUtil.USER_CUSTOMER){
                Intent intent = new Intent(LoginActivity.this,CustomerActivity.class);
                startActivity(intent);
                finish();
            }else{
                Intent intent = new Intent(LoginActivity.this,StaffActivity.class);
                startActivity(intent);
                finish();
            }
        }
       // getScreenWH();

        mSwitch = findViewById(R.id.switch1);
        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    compoundButton.setText("窗口端");
                    SpfUtil.setUserType(LoginActivity.this,SpfUtil.USER_STAFF);
                }else{
                    compoundButton.setText("用户端");
                    SpfUtil.setUserType(LoginActivity.this,SpfUtil.USER_CUSTOMER);
                }
            }
        });
        if(SpfUtil.getUserType(LoginActivity.this)==SpfUtil.USER_CUSTOMER){
            mSwitch.setChecked(false);
        }else{
            mSwitch.setChecked(true);
        }
    }



    private void getScreenWH() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        MyLog.i(TAG, "设备分辨率   w: " + screenWidth + "   h: " + screenHeight);
//        DisplayMetrics dm = new DisplayMetrics();
//        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
//        int screenHeight = dm.heightPixels;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        // Reset errors.
        mAccountView.setError(null);
        mWindowView.setError(null);

        // Store values at the time of the login attempt.
//        String account = mAccountView.getText().toString();
        final String window = mWindowView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(window) && !isWindowValid(window)) {
            mWindowView.setError(getString(R.string.error_invalid_window));
            focusView = mWindowView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(window)) {
            mWindowView.setError(getString(R.string.error_invalid_window));
            focusView = mWindowView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
                showProgress(true);
                LoginInput loginInput = new LoginInput();
                loginInput.worknum = window;
                loginInput.windownum = window;
                loginInput.device = Tools.getMacAddress();
                loginInput.type = (SpfUtil.getUserType(LoginActivity.this) == SpfUtil.USER_CUSTOMER?0:1);
                Call<UserMetter> call = HttpTools.getService().login(loginInput);
                call.enqueue(new Callback<UserMetter>() {
                    @Override
                    public void onResponse(Call<UserMetter> call, Response<UserMetter> response) {

                        if (response.code() == 200) {
                            if (response.body().code == 1) {
                                SpfUtil.saveLoginInfo(LoginActivity.this,response.body());
                                Intent intent = new Intent(LoginActivity.this,SpfUtil.getUserType(LoginActivity.this) == SpfUtil.USER_CUSTOMER? CustomerActivity.class:StaffActivity.class);
                                CommonUtils.finishActivity();
                                startActivity(intent);
                                finish();
                            } else {
                                showDialog(response.body().msg);
                            }
                        } else {
                            showDialog(response.message());
                        }

                    }

                    @Override
                    public void onFailure(Call<UserMetter> call, Throwable t) {

                        showDialog("请求超时,请稍后再试");

                    }
                });
        }
    }


    private void showDialog(String msg) {
        DialogFactory.warningDialog(LoginActivity.this, "提示", msg, "确定", new OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgress(false);
            }
        });

    }

    private boolean isAccountValid(String account) {
        return account.length() > 0;
    }

    private boolean isWindowValid(String window) {
        return window.length() > 0;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            CommonUtils.finishActivity();
        }
        return super.onKeyDown(keyCode, event);
    }
}

